package com.bookstore.servlet.client;

import com.bookstore.entity.User;
import com.bookstore.factory.ServiceFactory;
import com.bookstore.service.UserService;
import com.bookstore.servlet.BaseServlet;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;

@WebServlet("/client/user.do")
public class UserServlet  extends BaseServlet {
    UserService userService= ServiceFactory.getUserService();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        username=new String(username.getBytes("ISO-8859-1"),"UTF-8");
        String password = req.getParameter("password");
        User user = userService.LoginUser(username, password);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (user==null){
            writer.write(new Gson().toJson("0"));
        }else {
            req.getSession().setAttribute("user",user);
            writer.write(new Gson().toJson("1"));
        }
    }

    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username= req.getParameter("username");
        String password= req.getParameter("password");
        String gender= req.getParameter("gender");
        String email= req.getParameter("email");
        String telephone= req.getParameter("telephone");
        String introduce= req.getParameter("introduce");
        String activeCode= req.getParameter("activeCode");
        String state= req.getParameter("state");
        String role= req.getParameter("role");
        String registTime= req.getParameter("registTime");
        User user = new User(null, username, password, gender, email, telephone, introduce, activeCode, 1, 0, new Timestamp(System.currentTimeMillis()));
        System.out.println(user);
        int register = userService.register(user);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (register<=0){
            writer.write(new Gson().toJson("0"));
        }else {
            writer.write(new Gson().toJson("1"));
        }
    }

    protected void keepLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user =(User) req.getSession().getAttribute("user");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if (user==null){
            writer.write(new Gson().toJson("0"));
        }else {
            writer.write(new Gson().toJson(user));
        }
    }
}
